﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mads.CoreDomain;

namespace MADSite
{
  public partial class TicketsFin : System.Web.UI.Page
  {
    int id;
    FreeTicket[] massiveOfTickets;
    Station stationDep;
    Station stationArr;
    Station[] massiveOfStations;
    TrainManagerClient client = new TrainManagerClient();
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Request.Cookies.AllKeys.Contains("id"))
      {
        id = client.InitUser();
      }
      else
      {
        id = Int32.Parse(Request.Cookies["id"].Value);
      }
      HttpCookie cookie = new HttpCookie("id", id.ToString());
      Response.Cookies.Add(cookie);
      
      DateTime depTime;
      try
      {
        depTime = DateTime.Parse(Request.Cookies["date"].Value);
      }
      catch (Exception)
      {
        //HACK - should have returned an error
        depTime = DateTime.UtcNow;
      }
      
      massiveOfStations = client.GetStations(id);
      string depN = Request.Cookies["startPoint"].Value;
      string arrN = Request.Cookies["finishPoint"].Value;
      foreach (Station station in massiveOfStations)
      {
        if (station.Name == depN)
        {
          stationDep = station;
        }
        if (station.Name == arrN)
        {
          stationArr = station;
        }
      }
      massiveOfTickets = client.GetTickets(id, depTime, stationDep, stationArr);
    }

    /// <summary>
    /// Подтвердить покупку билета
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void confirmButton_Click(object sender, EventArgs e)
    {
      foreach (FreeTicket ticket in massiveOfTickets)
      {
        if (ticket.SitNumber == Int32.Parse(Request.Cookies["res"].Value))
        {
          if (client.BuyTicket(id, ticket, stationDep, stationArr, FIOTextBox.Text, PassportTextBox.Text))
          {
            Response.Redirect("ResultOK.aspx");
            break;
          }
        }
      }
      Response.Redirect("ResultFail.aspx");
    }

    /// <summary>
    /// Вернуться к выбору мест
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void prevButton_Click(object sender, EventArgs e)
    {
      Response.Redirect("Tickets3.aspx");
    }
  }
}